package com.novabluetooth.services;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

/**
 * Service for managing connection and data communication with a GATT server
 * hosted on a given Bluetooth LE device.
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class TJBluetoothLeService extends Service implements BluetoothServiceInterface {

	public SharedPreferences preferences;
	public SharedPreferences.Editor editor;
	public String deviceName;
	protected final static String TAG = "TJBluetoothLeService";

	private BluetoothManager mBluetoothManager;
	private BluetoothAdapter mBluetoothAdapter;
	private String mBluetoothDeviceAddress;
	protected BluetoothGatt mBluetoothGatt;
	private int mConnectionState = STATE_DISCONNECTED;

	private static final int STATE_DISCONNECTED = 0;
	private static final int STATE_CONNECTING = 1;
	private static final int STATE_CONNECTED = 2;

	public final static String ACTION_GATT_CONNECTED = "com.nova.bt_example.ACTION_GATT_CONNECTED";
	public final static String ACTION_GATT_DISCONNECTED = "com.nova.bt_example.ACTION_GATT_DISCONNECTED";
	public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.nova.bt_example.ACTION_GATT_SERVICES_DISCOVERED";
	public final static String ACTION_DATA_AVAILABLE = "com.nova.bt_example.ACTION_DATA_AVAILABLE";
	public final static String EXTRA_DATA = "com.nova.bt_example.le.EXTRA_DATA";

	public final static UUID serviceUUID = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
	public final static UUID writeCharactUUID = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb");
	public final static UUID readCharactUUID = UUID.fromString("0000fff4-0000-1000-8000-00805f9b34fb");
	BluetoothGattCharacteristic indicateGattCharact;
	public BluetoothGattCharacteristic muGattCharact;

	protected BluetoothGattCharacteristic readGattCharact;
	protected BluetoothGattCharacteristic writeGattCharact;
	private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

		@SuppressLint("NewApi")
		@Override
		public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
			String intentAction;
			if (newState == BluetoothProfile.STATE_CONNECTED) {
				intentAction = ACTION_GATT_CONNECTED;
				mConnectionState = STATE_CONNECTED;
				broadcastUpdate(intentAction);
				Log.e(TAG, "连接上GATT服务.");
				Log.e(TAG, "尝试启动discoverServices():" + mBluetoothGatt.discoverServices());

			} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
				intentAction = ACTION_GATT_DISCONNECTED;
				mConnectionState = STATE_DISCONNECTED;
				Log.i(TAG, "断开GATT服务.");
				broadcastUpdate(intentAction);
			}
		}

		@SuppressLint("NewApi")
		@Override
		public void onServicesDiscovered(BluetoothGatt gatt, final int status) {
			if (status == BluetoothGatt.GATT_SUCCESS) {
				servicesDiscovered();
				servicesDiscovered(status);
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						boolean ifSuccess = false;
						Log.e(TAG, "发送读取" + deviceName + "的指令 - status=" + ifSuccess);
						broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
					}
				},500);
			} else {
				Log.e(TAG, "onServicesDiscovered received: " + status);
			}
		}

		@Override
		public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
			if (status == BluetoothGatt.GATT_SUCCESS) {
				broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
			}
		}

		@Override
		public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
			System.out.println("获取数据");
			broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
		}

	};

	private void broadcastUpdate(final String action) {

		Log.e( TAG , "broadcastUpdate()"+action);
		final Intent intent = new Intent(action);
		sendBroadcast(intent);
	}

	boolean isHandler = true;

	private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
		final Intent intent = new Intent(action);

		byte[] byteData = characteristic.getValue();
		int i = characteristic.getIntValue(17, 0).intValue();
		// BluetoothLeService.this.postIntValue(17, i);
		System.out.println(byteData);
		Log.e("nova", byteData.toString());
		for (int ij = 0; ij < byteData.length; ij++) {
			Log.i("nova", byteData[ij] + "");
		}
		Log.e("broadcastUpdate()","数据" + byteArray2HexString(byteData, byteData.length));
		if (isHandler) {
		 
			if (isCorrectData(byteData)) {
				System.out.println(deviceName + "可以关闭蓝牙了");
				isHandler = false;
				Log.e(TAG, "检测到设备发送的数据");

				boolean ifSuccess = false;

				closeDevice();
				 
				intent.putExtra(EXTRA_DATA, String.valueOf(checkData));
				sendBroadcast(intent);
			} else {
				Log.e(TAG, "检测到的数据不符合规范");
			}
		}
	}

	protected String checkData;

	public class LocalBinder extends Binder {
		public TJBluetoothLeService getService() {
			return TJBluetoothLeService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {

		preferences = getSharedPreferences("nova_debug", Context.MODE_PRIVATE);
		editor = preferences.edit();

		deviceName = preferences.getString("deviceName", "");
		Log.e("TAG_onBind()", deviceName);
		return mBinder;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		close();
		return super.onUnbind(intent);
	}

	private final IBinder mBinder = new LocalBinder();

	/**
	 * Initializes a reference to the local Bluetooth adapter.
	 * 
	 * @return Return true if the initialization is successful.
	 */
	public boolean initialize() {
		// For API level 18 and above, get a reference to BluetoothAdapter
		// through
		// BluetoothManager.
		if (mBluetoothManager == null) {
			mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
			if (mBluetoothManager == null) {
				Log.e(TAG, "Unable to initialize BluetoothManager.");
				return false;
			}
		}

		mBluetoothAdapter = mBluetoothManager.getAdapter();
		if (mBluetoothAdapter == null) {
			Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
			return false;
		}
		return true;
	}

	/**
	 * Connects to the GATT server hosted on the Bluetooth LE device.
	 * 
	 * @param address
	 *            The device address of the destination device.
	 * 
	 * @return Return true if the connection is initiated successfully. The
	 *         connection result is reported asynchronously through the
	 *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
	 *         callback.
	 */
	public boolean connect(final String address) {

		if (mBluetoothAdapter == null || address == null) {
			Log.e(TAG, "BluetoothAdapter未初始化或未指定的地址.");
			return false;
		}

		// Previously connected device. Try to reconnect.
		if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
			Log.e(TAG, "试图使用一个现有的mBluetoothGatt连接.");

			if (mBluetoothGatt.connect()) {
				mConnectionState = STATE_CONNECTING;
				return true;
			} else {
				return false;
			}
		}

		final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		if (device == null) {
			Log.w(TAG, "Device not found.  Unable to connect.");
			return false;
		}
		mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
		// TODO 创建连接
		Log.d(TAG, "创建一个新的连接.");
		mBluetoothDeviceAddress = address;
		mConnectionState = STATE_CONNECTING;
		return true;
	}

	/**
	 * Disconnects an existing connection or cancel a pending connection. The
	 * disconnection result is reported asynchronously through the
	 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
	 * callback.
	 */
	public void disconnect() {
		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
			Log.w(TAG, "BluetoothAdapter not initialized");
			return;
		}
		mBluetoothGatt.disconnect();
	}

	/**
	 * After using a given BLE device, the app must call this method to ensure
	 * resources are released properly.
	 */
	public void close() {
		if (mBluetoothGatt == null) {
			return;
		}
		mBluetoothGatt.close();
		mBluetoothGatt = null;
	}

	/**
	 * Request a read on a given {@code BluetoothGattCharacteristic}. The read
	 * result is reported asynchronously through the
	 * {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
	 * callback.
	 * 
	 * @param characteristic
	 *            The characteristic to read from.
	 */
	public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
			Log.w(TAG, "BluetoothAdapter not initialized");
			return;
		}
		mBluetoothGatt.readCharacteristic(characteristic);
	}

	/**
	 * Enables or disables notification on a give characteristic.
	 * 
	 * @param characteristic
	 *            Characteristic to act on.
	 * @param enabled
	 *            If true, enable notification. False otherwise.
	 */
	public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
			Log.w(TAG, "BluetoothAdapter not initialized");
			return;
		}
		mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
	}

	/**
	 * Retrieves a list of supported GATT services on the connected device. This
	 * should be invoked only after {@code BluetoothGatt#discoverServices()}
	 * completes successfully.
	 * 
	 * @return A {@code List} of supported services.
	 */
	public List<BluetoothGattService> getSupportedGattServices() {
		if (mBluetoothGatt == null)
			return null;

		return mBluetoothGatt.getServices();
	}

	/**
	 * 16进制转换成byte[]
	 * 
	 * @param hexString
	 * @return
	 */
	public byte[] String2Byte(String hexString) {
		if (hexString.length() % 2 == 1)
			return null;
		byte[] ret = new byte[hexString.length() / 2];
		for (int i = 0; i < hexString.length(); i += 2) {
			ret[i / 2] = Integer.decode("0x" + hexString.substring(i, i + 2)).byteValue();
		}
		return ret;
	}

	public boolean writeDataToDevice(String data) {

		byte[] toD = String2Byte(data);
		int storedLevel = writeGattCharact.getWriteType();
		Log.e(TAG, "storedLevel() - storedLevel=" + storedLevel);
		writeGattCharact.setValue(toD);

		writeGattCharact.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
		boolean ifSuccess = mBluetoothGatt.writeCharacteristic(writeGattCharact);
		return ifSuccess;
	}

	public boolean writeDataToDevice(byte[] data) {
		writeGattCharact.setValue(data);

		writeGattCharact.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
		boolean ifSuccess = mBluetoothGatt.writeCharacteristic(writeGattCharact);
		return ifSuccess;
	}


	/**
	 * 数据解析
	 * 
	 * @param buffer
	 * @return
	 * @author 鹿云龙
	 * @date 2015年9月14日 下午4:40:23
	 */
	protected boolean ifSuccess = false;
	public synchronized boolean isCorrectData(byte[] buffer) {
		return isRightData(buffer);
	}

	public static String byteArray2HexString(byte[] bytes, int byteSize) {

		byte[] buf = bytes;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < byteSize; i++) {
			String str = Integer.toHexString(buf[i] & 0xFF);
			if (str.length() < 2) {
				str = '0' + str;
			}
			str = str.toUpperCase();
			sb.append(str);
		}
		return sb.toString();
	}

	 
	@Override
	public void servicesDiscovered() {
		
	}

	@Override
	public void servicesDiscovered(int status) {

	}

	public boolean writeDataToDevice1(String data, BluetoothGattCharacteristic characteristic) {
		boolean isEnableNotification = mBluetoothGatt.setCharacteristicNotification(characteristic, true);
		if (isEnableNotification) {
			List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
			if (descriptorList != null && descriptorList.size() > 0) {
				for (BluetoothGattDescriptor descriptor : descriptorList) {
					descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
					mBluetoothGatt.writeDescriptor(descriptor);
				}
			}
		}
		byte[] toD = String2Byte(data);
		int storedLevel = writeGattCharact.getWriteType();
		Log.e(TAG, "storedLevel() - storedLevel=" + storedLevel);
		writeGattCharact.setValue(toD);

		writeGattCharact.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
		boolean ifSuccess = mBluetoothGatt.writeCharacteristic(writeGattCharact);
		return ifSuccess;
	}

	@Override
	public boolean isRightData(byte[] buffer) {
		return ifSuccess;
		
	}

	@Override
	public void closeDevice() {
		
	}
}